﻿package mvc_model
{
	import flash.events.MouseEvent;
	import flash.events.Event;
	import flash.net.FileReference;
	import flash.net.FileFilter;
	import flash.net.URLRequest;
	
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileReference;

	public class UploadFile extends Model
	{
		private var _fileReference:FileReference;
		private var _selectedPath:String;
		
		public function UploadFile()
		{
			_fileReference = new FileReference();
			_fileReference.addEventListener(Event.SELECT, selectHandler);
			_fileReference.addEventListener(Event.CANCEL, cancelHandler);
			_fileReference.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			_fileReference.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			_fileReference.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityHandler);
			_fileReference.addEventListener(Event.COMPLETE, completeHandler);
		}
		
		public function get fileReference():FileReference
		{
			return _fileReference;
		}
		
		public function get fileName():String
		{
			return _fileReference.name;
		}
		
		public function browseHandler(event:MouseEvent = null):void 
		{
			_fileReference.browse([new FileFilter("Image Files","*.jpg;*.gif;*.png")]);
		}
		
		public function uploadHandler(event:MouseEvent = null):void 
		{
			_fileReference.upload(new URLRequest("http://localhost/simpleFileUpload.php?username=" + _fileReference.name));
		}
		
		private function selectHandler(event:Event):void 
		{
			_selectedPath = _fileReference.name;
			dispatchEvent(new Event(Model.MODEL_CHANGE));
		}
		
		override protected function updateData():void
		{
		}
		
		override protected function dataLoaded(event:Event):void
		{
		}
		
		public function get selectedPath():String
		{
			return _selectedPath;
		}
		
		private function cancelHandler(event:Event):void 
		{
			//trace("Canceled");
		}
		
		private function progressHandler(event:ProgressEvent):void 
		{
			//trace("file uploading\nprogress (bytes): " + event.bytesLoaded + " / " + event.bytesTotal);
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void 
		{
			//trace("an IO error occurred");
		}
		private function securityHandler(event:SecurityErrorEvent):void 
		{
			//trace("a security error occurred");
		}
		
		private function completeHandler(event:Event):void 
		{
			//trace("the file has uploaded");
		}
	}
}